import React, { useState, useEffect } from 'react';
import { useStore } from '@/hooks'
import { observer } from 'mobx-react-lite';
import { Timeline, Loading, Button, Icon } from '@alifd/next';
import styles from './PushMessage.module.scss'
import { DATETIMES_TEXT } from '../stores/definitions';
import { t } from '@lingui/macro';

const TimelineItem = Timeline.Item;

const PushMessage = ({ modal }) => {
  const { show, record } = modal;
  const { orderStore: store } = useStore();
  const [state, setState] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const res = await store.getLogs({ search: { targetId: `${record?.id}-send` } });
      setState(res.map((p) => ({ ...p, unfold: false })));
      setLoading(false);
    })();
  }, []);

  const handleUnfold = (i) => {
    const cloneState = [...state];
    cloneState[i].unfold = !cloneState[i].unfold;
    setState(cloneState);
  };

  return (
    <>
      <Loading
        visible={loading}
        className={styles.loading}
      >
        <Timeline>
          {state.map(({ ts, title, unfold }, i) => {
            const isPushBatch = title.includes('成员:');
            const members = title?.split('、');
            return (
              <TimelineItem
                key={ts}
                title={
                  isPushBatch ?
                    <>
                      <div className={unfold ? styles.defaultTitle : styles.title}>
                        <span>{`推送人数：${members.length}(人)，${title}`}</span>
                      </div>
                      <Button type="primary" text onClick={() => handleUnfold(i)}>
                        {unfold ? <Icon type="arrow-up" /> : <Icon type="arrow-down" />}
                        {t`展开`}
                      </Button>
                    </> : <>{title}</>
                }
                timeLeft={DATETIMES_TEXT(ts)}
              />);
          })}
        </Timeline>
      </Loading>
    </>
  );
};

export default observer(PushMessage);
